<template>
  <div class="home-container">
    <!-- 顶部：左侧分类菜单 + 中间轮播 + 右侧用户面板 -->
    <section class="hero-section">
              <!-- 桌面端布局 -->
        <div class="hero-grid desktop-only">
        <!-- 左：分类菜单 -->
        <aside class="category-menu">
          <ul>
            <li
              v-for="category in categories"
              :key="category.typeId"
              class="category-menu-item"
              @click="navigateToCategory(category.typeId)"
              @mouseenter="handleCategoryHover(category.typeId)"
              @mouseleave="handleCategoryLeave"
            >
              <span class="name">{{ category.typeName }}</span>
              <el-icon class="arrow"><ArrowRight /></el-icon>
              
              <!-- 悬停显示的商品列表 -->
              <div 
                v-if="hoveredCategory === category.typeId && categoryProducts.length > 0"
                class="category-products-popup"
                @mouseenter="keepPopupOpen = true"
                @mouseleave="handlePopupLeave"
              >
                <div class="popup-header">
                  <h4>{{ category.typeName }}商品</h4>
                </div>
                <div class="products-list">
                  <div 
                    v-for="product in categoryProducts.slice(0, 8)"
                    :key="product.shoeId"
                    class="product-item"
                    @click.stop="navigateToProduct(product.shoeId)"
                  >
                    <span class="product-name">{{ product.name }}</span>
                    <span class="product-price">¥{{ product.price }}</span>
                  </div>
                  <div v-if="categoryProducts.length > 8" class="more-products">
                    <span @click.stop="navigateToCategory(category.typeId)">查看更多...</span>
                  </div>
                </div>
              </div>
            </li>
          </ul>
        </aside>

        <!-- 中：轮播图 -->
        <div class="hero-carousel">
          <el-carousel :height="carouselHeight" indicator-position="outside" :interval="5000" arrow="hover">
            <el-carousel-item v-for="banner in banners" :key="banner.id">
              <div class="banner-container" @click="handleBannerClick(banner)">
                <img :src="banner.image" :alt="banner.title" class="banner-image" />
                <div class="banner-overlay">
                  <h3>{{ banner.title }}</h3>
                  <p>{{ banner.subtitle }}</p>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>

        <!-- 右：用户面板 -->
        <aside class="user-panel">
          <div class="user-card">
            <img
              class="avatar"
              :src="
                authStore.isLoggedIn
                  ? authStore.user?.avatarUrl || '/images/avatars/default-80.png'
                  : '/images/avatars/default-80.png'
              "
              alt="avatar"
            />
            <div class="greeting">
              <p class="hello">Hi，{{ authStore.isLoggedIn ? displayName : '欢迎来到方舟鞋城' }}</p>
              <div v-if="!authStore.isLoggedIn" class="auth-actions">
                <el-button size="small" type="danger" @click="$router.push('/auth/login')"
                  >立即登录</el-button
                >
                <el-button size="small" @click="$router.push('/auth/register')">免费注册</el-button>
              </div>
              <div v-else class="user-actions">
                <el-button size="small" @click="$router.push('/user')">个人中心</el-button>
                <el-button size="small" type="primary" @click="$router.push('/orders')"
                  >我的订单</el-button
                >
              </div>
            </div>
          </div>

          <div class="quick-links">
            <div class="ql-item" @click="$router.push('/cart')">
              <el-icon><ShoppingCart /></el-icon>
              <span>购物车</span>
            </div>
            <div class="ql-item" @click="$router.push('/user/address')">
              <el-icon><Document /></el-icon>
              <span>收货地址</span>
            </div>
            <div class="ql-item" @click="$router.push('/brands')">
              <el-icon><Goods /></el-icon>
              <span>品牌馆</span>
            </div>
          </div>

          <div class="right-promos">
            <div
              class="promo"
              v-for="p in rightPromos"
              :key="p.title"
              @click="$router.push(p.link)"
            >
              <img :src="p.image" :alt="p.title" />
              <span>{{ p.title }}</span>
            </div>
          </div>
        </aside>
      </div>

      <!-- 移动端布局 -->
      <div class="mobile-hero mobile-only">
        <!-- 移动端轮播图 -->
        <div class="mobile-carousel">
          <el-carousel :height="carouselHeight" indicator-position="outside" :interval="5000" arrow="never">
            <el-carousel-item v-for="banner in banners" :key="banner.id">
              <div class="mobile-banner-container" @click="handleBannerClick(banner)">
                <img :src="banner.image" :alt="banner.title" class="mobile-banner-image" />
                <div class="mobile-banner-overlay">
                  <h3>{{ banner.title }}</h3>
                  <p>{{ banner.subtitle }}</p>
                </div>
              </div>
            </el-carousel-item>
          </el-carousel>
        </div>

        <!-- 移动端分类菜单 -->
        <div class="mobile-category-menu">
          <div class="mobile-category-header">
            <h3>商品分类</h3>
            <el-button type="text" @click="showMobileCategoryDrawer = true">
              全部分类 <el-icon><ArrowRight /></el-icon>
            </el-button>
          </div>
          <div class="mobile-category-grid">
            <div
              v-for="category in categories.slice(0, 8)"
              :key="category.typeId"
              class="mobile-category-item"
              @click="navigateToCategory(category.typeId)"
            >
              <div class="mobile-category-icon">
                <el-icon><Goods /></el-icon>
              </div>
              <span class="mobile-category-name">{{ category.typeName }}</span>
            </div>
          </div>
        </div>

        <!-- 移动端用户快捷操作 -->
        <div class="mobile-user-actions">
          <div class="mobile-user-card" v-if="authStore.isLoggedIn">
            <img
              class="mobile-avatar"
              :src="authStore.user?.avatarUrl || '/images/avatars/default-80.png'"
              alt="avatar"
            />
            <div class="mobile-user-info">
              <p class="mobile-hello">Hi，{{ displayName }}</p>
              <div class="mobile-user-buttons">
                <el-button size="small" @click="$router.push('/user')">个人中心</el-button>
                <el-button size="small" type="primary" @click="$router.push('/orders')">我的订单</el-button>
              </div>
            </div>
          </div>
          <div class="mobile-auth-card" v-else>
            <div class="mobile-auth-info">
              <p class="mobile-welcome">欢迎来到方舟鞋城</p>
              <div class="mobile-auth-buttons">
                <el-button size="small" type="danger" @click="$router.push('/auth/login')">立即登录</el-button>
                <el-button size="small" @click="$router.push('/auth/register')">免费注册</el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 移动端快捷链接 -->
        <div class="mobile-quick-links">
          <div class="mobile-quick-grid">
            <div class="mobile-quick-item" @click="$router.push('/cart')">
              <el-icon><ShoppingCart /></el-icon>
              <span>购物车</span>
            </div>
            <div class="mobile-quick-item" @click="$router.push('/user/address')">
              <el-icon><Document /></el-icon>
              <span>收货地址</span>
            </div>
            <div class="mobile-quick-item" @click="$router.push('/brands')">
              <el-icon><Goods /></el-icon>
              <span>品牌馆</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 移动端分类抽屉 -->
      <el-drawer
        v-model="showMobileCategoryDrawer"
        title="全部商品分类"
        direction="ltr"
        size="80%"
        class="mobile-category-drawer"
      >
        <div class="mobile-category-list">
          <div
            v-for="category in categories"
            :key="category.typeId"
            class="mobile-category-list-item"
            @click="handleMobileCategoryClick(category.typeId)"
          >
            <span class="category-name">{{ category.typeName }}</span>
            <el-icon><ArrowRight /></el-icon>
          </div>
        </div>
      </el-drawer>
    </section>

    <!-- 快速导航 -->
    <section class="quick-nav-section">
      <div class="quick-nav-grid">
        <div
          v-for="nav in quickNavs"
          :key="nav.path"
          class="quick-nav-item"
          @click="$router.push(nav.path)"
        >
          <div class="nav-icon">
            <el-icon><component :is="nav.icon" /></el-icon>
          </div>
          <span class="nav-text">{{ nav.name }}</span>
        </div>
      </div>
    </section>

    <!-- 分类导航 -->
    <section class="category-section">
      <div class="section-header">
        <h2 class="section-title">热门分类</h2>
        <el-button type="text" @click="$router.push('/products')" class="more-btn">
          更多分类 <el-icon><ArrowRight /></el-icon>
        </el-button>
      </div>
      <div class="category-grid" v-loading="categoriesLoading" element-loading-text="加载中...">
        <div
          v-for="category in categories.slice(0, 8)"
          :key="category.typeId"
          class="category-item"
          @click="navigateToCategory(category.typeId)"
        >
          <div class="category-icon" :style="{ backgroundColor: getCategoryIcon(category.typeId).color }">
            <el-icon><component :is="getCategoryIcon(category.typeId).icon" /></el-icon>
          </div>
          <span class="category-name">{{ category.typeName }}</span>
        </div>
      </div>
    </section>

    <!-- 热销商品 -->
    <section class="products-section">
      <div class="section-header">
        <h2 class="section-title">热销商品</h2>
        <el-button type="text" @click="$router.push('/products')" class="more-btn">
          查看更多
          <el-icon>
            <ArrowRight />
          </el-icon>
        </el-button>
      </div>
      <div class="products-grid" v-loading="hotProductsLoading" element-loading-text="加载中...">
        <ProductCard
          v-for="product in hotProducts"
          :key="product.shoeId"
          :product="product"
          @add-to-cart="handleAddToCart"
        />
      </div>
    </section>

    <!-- 新品推荐 -->
    <section class="products-section">
      <div class="section-header">
        <h2 class="section-title">新品推荐</h2>
        <el-button type="text" @click="$router.push('/products')" class="more-btn">
          查看更多
          <el-icon>
            <ArrowRight />
          </el-icon>
        </el-button>
      </div>
      <div class="products-grid" v-loading="newProductsLoading" element-loading-text="加载中...">
        <ProductCard
          v-for="product in newProducts"
          :key="product.shoeId"
          :product="product"
          @add-to-cart="handleAddToCart"
        />
      </div>
    </section>

    <!-- 品牌推荐 -->
    <section class="brands-section">
      <div class="section-header">
        <h2 class="section-title">品牌推荐</h2>
        <el-button type="text" @click="$router.push('/products')" class="more-btn">
          更多品牌
          <el-icon>
            <ArrowRight />
          </el-icon>
        </el-button>
      </div>
      <div class="brands-grid" v-loading="brandsLoading" element-loading-text="加载中...">
        <div
          v-for="brand in brands"
          :key="(brand as any).brand_id || (brand as any).id"
          class="brand-item"
          @click="navigateToBrand((brand as any).brand_id || (brand as any).id)"
        >
          <div class="brand-logo">
            <img
              :src="(brand as any).brand_logo || (brand as any).logo || '/brand-default.png'"
              :alt="(brand as any).brand_name || (brand as any).name"
            />
          </div>
          <span class="brand-name">{{ (brand as any).brand_name || (brand as any).name }}</span>
        </div>
      </div>
    </section>

    <!-- 个性化推荐 -->
    <section class="products-section" v-if="recommendedProducts.length > 0">
      <div class="section-header">
        <h2 class="section-title">为您推荐</h2>
        <el-button type="text" @click="$router.push('/products')" class="more-btn">
          查看更多
          <el-icon>
            <ArrowRight />
          </el-icon>
        </el-button>
      </div>
      <div
        class="products-grid"
        v-loading="recommendedProductsLoading"
        element-loading-text="加载中..."
      >
        <ProductCard
          v-for="product in recommendedProducts"
          :key="product.shoeId"
          :product="product"
          @add-to-cart="handleAddToCart"
        />
      </div>
    </section>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { productService, advertisementService } from '@/api'
import { useCartStore } from '@/stores/cart'
import { useAuthStore } from '@/stores/auth'
import { useAuthModalStore } from '@/stores/authModal'
import ProductCard from '@/components/ProductCard.vue'
import type { Shoes, Types, Brand, Product, ProductVO, Advertisement } from '@/types'
import { createLogger } from '@/utils/logger'
import {
  ShoppingCart,
  User,
  Document,
  Setting,
  Goods,
  Search,
  Star,
  Ticket,
  ArrowRight,
  // 分类相关图标
   Football,
   Briefcase,
   Trophy,
   Present,
   Position,
   Medal,
   TrendCharts,
   StarFilled
} from '@element-plus/icons-vue'
import { shouldShowDiscountAd } from '@/utils/discountUtils'

const router = useRouter()
const cartStore = useCartStore()
const homeLogger = createLogger('HomePage')
const authStore = useAuthStore()
const authModal = useAuthModalStore()

// 快速导航
const quickNavs = ref([
  { name: '商品列表', path: '/products', icon: 'Goods' },
  { name: '购物车', path: '/cart', icon: 'ShoppingCart' },
  { name: '个人中心', path: '/user', icon: 'User' },
  { name: '我的订单', path: '/orders', icon: 'Document' },
  { name: '我的收藏', path: '/user/wishlist', icon: 'Star' },
  { name: '优惠券', path: '/user/coupon', icon: 'Ticket' },
  { name: '账户安全', path: '/user/security', icon: 'Setting' },
  { name: '管理后台', path: '/admin', icon: 'Setting' },
])

// 数据状态
const banners = ref<Advertisement[]>([])

const categories = ref<Types[]>([])
const brands = ref<Brand[]>([])
const hotProducts = ref<ProductVO[]>([])
const newProducts = ref<ProductVO[]>([])
const recommendedProducts = ref<ProductVO[]>([])

// 分类悬停相关数据
const hoveredCategory = ref<number | null>(null)
const categoryProducts = ref<ProductVO[]>([])
const keepPopupOpen = ref(false)
const hoverTimer = ref<number | null>(null)

// 移动端分类抽屉
const showMobileCategoryDrawer = ref(false)

// 右侧促销位与欢迎名称
const rightPromos = ref([
  { title: '限时秒杀', image: '/images/banners/banner-1.jpg', link: '/products' },
  { title: '今日热卖', image: '/images/banners/banner-2.jpg', link: '/products' },
])

const displayName = computed(() => authStore.user?.username || authStore.user?.nickname || '用户')

// 加载状态
const categoriesLoading = ref(false)
const brandsLoading = ref(false)
const hotProductsLoading = ref(false)
const newProductsLoading = ref(false)
const recommendedProductsLoading = ref(false)

// 轮播图高度状态
const carouselHeight = ref('400px') // 默认高度

// 根据分类数量计算轮播图高度
const updateCarouselHeight = () => {
  // 每个分类项目42.4px高度
  const itemHeight = 42.4
  const categoryCount = categories.value.length
  
  if (categoryCount > 0) {
    const calculatedHeight = Math.max(categoryCount * itemHeight, 200) // 最小高度200px
    carouselHeight.value = `${calculatedHeight}px`
  }
}

// 监听分类数据变化
const setupHeightObserver = () => {
  // 使用watch监听categories数组变化
  watch(categories, () => {
    updateCarouselHeight()
  }, { immediate: true })
}

// 加载首页数据
const loadHomeData = async () => {
  try {
    // 加载广告轮播图
    try {
      console.log('开始获取广告数据...')
      const bannersResponse = await advertisementService.getBannerAdvertisements()
      console.log('广告API响应:', bannersResponse)
      
      if (bannersResponse.data.code === 200) {
        const bannersData = bannersResponse.data.data || []
        console.log('获取到的广告数据:', bannersData)
        banners.value = bannersData.map((ad: any) => ({
          id: ad.id,
          image: ad.imageUrl,
          title: ad.title,
          subtitle: ad.description || '',
          link: ad.linkUrl || '/products',
        }))
        homeLogger.info(`成功加载${banners.value.length}个广告`)
      } else {
        console.error('广告API返回错误:', bannersResponse.data)
        homeLogger.error('广告API返回错误:', bannersResponse.data.msg)
        // 使用默认广告数据
        banners.value = [
          {
            id: 1,
            image: '/images/banners/banner-1.jpg',
            title: '春季新品上市',
            subtitle: '限时8折起',
            link: '/products',
          },
          {
            id: 2,
            image: '/images/banners/banner-2.jpg',
            title: '限时折扣',
            subtitle: '全场5折起',
            link: '/products',
          },
          {
            id: 3,
            image: '/images/banners/banner-3.jpg',
            title: '品牌特卖',
            subtitle: '大牌鞋履特价',
            link: '/products',
          },
        ].filter(banner => shouldShowDiscountAd(banner.subtitle))
      }
    } catch (error) {
      console.error('获取广告失败:', error)
      homeLogger.error('获取广告失败:', error)
      // 使用默认广告数据
      banners.value = [
        {
          id: 1,
          image: '/images/banners/banner-1.jpg',
          title: '春季新品上市',
          subtitle: '限时8折起',
          link: '/products',
        },
        {
          id: 2,
          image: '/images/banners/banner-2.jpg',
          title: '限时折扣',
          subtitle: '全场5折起',
          link: '/products',
        },
        {
          id: 3,
          image: '/images/banners/banner-3.jpg',
          title: '品牌特卖',
          subtitle: '大牌鞋履特价',
          link: '/products',
        },
      ].filter(banner => shouldShowDiscountAd(banner.subtitle))
    }

    // 加载分类
    categoriesLoading.value = true
    try {
      console.log('开始获取分类数据...')
      const categoriesResponse = await productService.getProductTypes()
      console.log('分类API响应:', categoriesResponse)
      console.log('分类API响应状态:', categoriesResponse.status)
      console.log('分类API响应数据:', categoriesResponse.data)
      
      if (categoriesResponse.data.code === 200) {
        const typesData = categoriesResponse.data.data || []
        console.log('获取到的分类数据:', typesData)
        categories.value = typesData
        console.log('设置后的categories数组:', categories.value)
        console.log('categories数组长度:', categories.value.length)
        homeLogger.info(`成功加载${categories.value.length}个分类`)
      } else {
        console.error('分类API返回错误:', categoriesResponse.data)
        homeLogger.error('分类API返回错误:', categoriesResponse.data.msg)
        ElMessage.error('获取分类数据失败: ' + categoriesResponse.data.msg)
      }
    } catch (error) {
      console.error('获取分类失败:', error)
      homeLogger.error('获取分类失败:', error)
      ElMessage.error('连接服务器失败，请检查网络连接')
    } finally {
      categoriesLoading.value = false
    }

    // 加载品牌
    brandsLoading.value = true
    try {
      const brandsResponse = await productService.getProductBrands()
      if (brandsResponse.data.code === 200) {
        const baseUrl = 'http://localhost:8083'
        brands.value = brandsResponse.data.data.slice(0, 6).map((brand: any) => ({
          ...brand,
          brand_logo: brand.brand_logo && brand.brand_logo.startsWith('/') 
            ? baseUrl + brand.brand_logo 
            : brand.brand_logo
        }))
      }
    } catch (error) {
      homeLogger.error('获取品牌失败:', error)
      // 使用模拟数据
      brands.value = [
        {
          id: 1,
          name: 'Nike',
          description: '',
          logo: '/brand-nike.png',
          website: '',
          status: 'active',
          sort: 1,
          createTime: '',
          updateTime: '',
        },
        {
          id: 2,
          name: 'Adidas',
          description: '',
          logo: '/brand-adidas.png',
          website: '',
          status: 'active',
          sort: 2,
          createTime: '',
          updateTime: '',
        },
        {
          id: 3,
          name: 'Puma',
          description: '',
          logo: '/brand-puma.png',
          website: '',
          status: 'active',
          sort: 3,
          createTime: '',
          updateTime: '',
        },
        {
          id: 4,
          name: 'New Balance',
          description: '',
          logo: '/brand-nb.png',
          website: '',
          status: 'active',
          sort: 4,
          createTime: '',
          updateTime: '',
        },
        {
          id: 5,
          name: 'Converse',
          description: '',
          logo: '/brand-converse.png',
          website: '',
          status: 'active',
          sort: 5,
          createTime: '',
          updateTime: '',
        },
        {
          id: 6,
          name: 'Vans',
          description: '',
          logo: '/brand-vans.png',
          website: '',
          status: 'active',
          sort: 6,
          createTime: '',
          updateTime: '',
        },
      ] as unknown as Brand[]
    } finally {
      brandsLoading.value = false
    }

    // 加载热销商品 - 按销量降序排列
    hotProductsLoading.value = true
    try {
      const hotProductsResponse = await productService.searchProducts('', 1, 8, {
        sortBy: 'sales',
        sortOrder: 'desc'
      })
      if (hotProductsResponse.data.code === 200) {
        hotProducts.value = (hotProductsResponse.data.data.list as unknown as ProductVO[]) || []
      }
    } catch (error) {
      homeLogger.error('获取热门商品失败:', error)
      // 使用模拟数据
      hotProducts.value = generateMockProducts(8) as unknown as ProductVO[]
    } finally {
      hotProductsLoading.value = false
    }

    // 加载新品推荐 - 按商品ID降序排列（最新添加的商品）
    newProductsLoading.value = true
    try {
      const newProductsResponse = await productService.searchProducts('', 1, 8, {
        // 由于数据库中launch_date为null，使用默认排序（按ID降序）获取最新商品
      })
      if (newProductsResponse.data.code === 200) {
        newProducts.value = (newProductsResponse.data.data.list as unknown as ProductVO[]) || []
      }
    } catch (error) {
      homeLogger.error('获取新品失败:', error)
      // 使用模拟数据
      newProducts.value = generateMockProducts(8) as unknown as ProductVO[]
    } finally {
      newProductsLoading.value = false
    }

    // 如果已登录，加载个性化推荐
    if (authStore.isLoggedIn) {
      recommendedProductsLoading.value = true
      try {
        const recommendedResponse = await productService.searchProducts('', 1, 8)
        if (recommendedResponse.data.code === 200) {
          recommendedProducts.value =
            (recommendedResponse.data.data.list as unknown as ProductVO[]) || []
        }
      } catch (error) {
        homeLogger.error('获取推荐商品失败:', error)
        // 使用模拟数据
        recommendedProducts.value = generateMockProducts(8) as unknown as ProductVO[]
      } finally {
        recommendedProductsLoading.value = false
      }
    }
  } catch (error) {
    homeLogger.error('加载首页数据失败:', error)
    ElMessage.error('加载首页数据失败')
  }
}

// 生成模拟商品数据
const generateMockProducts = (count: number): Shoes[] => {
  const mockProducts: Shoes[] = []
  for (let i = 1; i <= count; i++) {
    mockProducts.push({
      shoeId: i,
      serialNumber: `SH${String(i).padStart(4, '0')}`,
      name: `时尚运动鞋 ${i}`,
      price: Math.floor(Math.random() * 500) + 200,
      discountPrice: Math.floor(Math.random() * 300) + 150,
      launchDate: new Date().toISOString(),
      originPlace: '中国',
      gender: Math.random() > 0.5 ? '男' : '女',
      description: '舒适透气，时尚百搭',
      detailedInfo: '采用优质材料制作，舒适透气，适合日常穿着和运动',
      itemPoints: Math.floor(Math.random() * 100) + 50,
      status: 'active',
      productImageUrl: `/images/products/mock-${i}.jpg`,
      salesVolume: Math.floor(Math.random() * 1000) + 100,
      brand_id: Math.floor(Math.random() * 6) + 1,
      typeId: Math.floor(Math.random() * 8) + 1,
    })
  }
  return mockProducts
}

// 获取分类图标
const getCategoryIcon = (typeId: number) => {
  // 根据分类ID返回不同的图标组件和颜色
  const iconMap: { [key: number]: { icon: any, color: string } } = {
    1: { icon: Football, color: '#FF6B6B' },      // 运动
    2: { icon: Goods, color: '#4ECDC4' },         // 休闲
    3: { icon: Briefcase, color: '#45B7D1' },     // 商务
    4: { icon: Present, color: '#96CEB4' },       // 时尚
    5: { icon: Position, color: '#FFEAA7' },      // 户外
    6: { icon: Medal, color: '#DDA0DD' },         // 经典
    7: { icon: TrendCharts, color: '#98D8C8' },   // 潮流
    8: { icon: StarFilled, color: '#F7DC6F' }     // 限量
  }
  
  return iconMap[typeId] || { icon: Goods, color: '#CCCCCC' }
}

// 导航方法
const navigateToCategory = (categoryId: number) => {
  router.push(`/category/${categoryId}`)
}

const navigateToBrand = (brandId: number) => {
  router.push(`/brand/${brandId}`)
}

const navigateToProduct = (productId: number) => {
  router.push(`/product/${productId}`)
}

// 分类悬停处理方法
const handleCategoryHover = async (categoryId: number) => {
  // 清除之前的定时器
  if (hoverTimer.value) {
    clearTimeout(hoverTimer.value)
  }
  
  hoveredCategory.value = categoryId
  keepPopupOpen.value = false
  
  try {
    // 获取该分类下的商品列表（只获取前10个）
    const response = await productService.searchProducts('', 1, 10, { typeId: categoryId })
    if (response.data.code === 200) {
      categoryProducts.value = response.data.data.list || []
    }
  } catch (error) {
    homeLogger.error('获取分类商品失败:', error)
    categoryProducts.value = []
  }
}

const handleCategoryLeave = () => {
  if (!keepPopupOpen.value) {
    hoverTimer.value = setTimeout(() => {
      hoveredCategory.value = null
      categoryProducts.value = []
    }, 200) // 200ms延迟，避免鼠标快速移动时闪烁
  }
}

const handlePopupLeave = () => {
  keepPopupOpen.value = false
  hoverTimer.value = setTimeout(() => {
    hoveredCategory.value = null
    categoryProducts.value = []
  }, 200)
}

const handleBannerClick = (banner: any) => {
  if (banner.link) {
    router.push(banner.link)
  }
}

const handleAddToCart = async (product: Product | Shoes | ProductVO) => {
  const shoeId = (product as any).shoeId ?? (product as any).id
  const result = await cartStore.addToCart(shoeId, 1)
  if (result.success) {
    ElMessage.success('已添加到购物车')
  } else {
    if ((result as any).needLogin) {
      authModal.openLogin('/cart', '登录后即可将商品加入购物车')
    } else {
      ElMessage.error(result.error || '添加失败')
    }
  }
}

// 移动端分类抽屉点击处理
const handleMobileCategoryClick = (categoryId: number) => {
  navigateToCategory(categoryId)
  showMobileCategoryDrawer.value = false
}

// 页面加载
onMounted(async () => {
  await nextTick()
  loadHomeData()
  
  // 设置高度监听
  setupHeightObserver()
})
</script>

<style scoped lang="scss">
.home-container {
  max-width: none;
  margin: 0 0;
  padding: 0;

  .hero-section {
    margin-bottom: 30px;

    .hero-grid {
      display: grid;
      grid-template-columns: 240px 1fr 280px;
      gap: 16px;
    }

    .category-menu {
      background: #fff;
      border-radius: 6px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
      padding: 8px 0;
      position: relative;
      ul {
        list-style: none;
        margin: 0;
        padding: 0;
      }
      .category-menu-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px 16px;
        font-size: 14px;
        color: #333;
        cursor: pointer;
        transition: background 0.2s ease;
        position: relative;
        .arrow {
          color: #bbb;
        }
        &:hover {
          background: #f5f5f5;
          .arrow {
            color: #ff1e32;
          }
        }
        
        // 悬停商品弹出层
        .category-products-popup {
          position: absolute;
          left: 100%;
          top: 0;
          width: 320px;
          background: #fff;
          border-radius: 8px;
          box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
          border: 1px solid #e0e0e0;
          z-index: 1000;
          
          .popup-header {
            padding: 12px 16px;
            border-bottom: 1px solid #f0f0f0;
            background: #fafafa;
            border-radius: 8px 8px 0 0;
            
            h4 {
              margin: 0;
              font-size: 14px;
              font-weight: 600;
              color: #333;
            }
          }
          
          .products-list {
            max-height: 300px;
            overflow-y: auto;
            
            .product-item {
              display: flex;
              justify-content: space-between;
              align-items: center;
              padding: 10px 16px;
              border-bottom: 1px solid #f5f5f5;
              cursor: pointer;
              transition: background 0.2s ease;
              
              &:hover {
                background: #f8f9fa;
              }
              
              &:last-child {
                border-bottom: none;
              }
              
              .product-name {
                flex: 1;
                font-size: 13px;
                color: #333;
                white-space: nowrap;
                
                text-overflow: ellipsis;
                margin-right: 12px;
              }
              
              .product-price {
                font-size: 13px;
                color: #ff5a00;
                font-weight: 600;
              }
            }
            
            .more-products {
              padding: 10px 16px;
              text-align: center;
              border-top: 1px solid #f0f0f0;
              
              span {
                color: #ff5a00;
                font-size: 13px;
                cursor: pointer;
                
                &:hover {
                  text-decoration: underline;
                }
              }
            }
          }
        }
      }
    }

    .hero-carousel {
      border-radius: 6px;
      
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

      .banner-container {
        position: relative;
        cursor: pointer;
        height: 100%;

        .banner-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .banner-overlay {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
          color: white;
          padding: 40px 20px 20px;
          text-align: center;

          h3 {
            font-size: 24px;
            font-weight: bold;
            margin: 0 0 8px 0;
          }
          p {
            font-size: 14px;
            margin: 0;
            opacity: 0.9;
          }
        }
      }
    }

    .user-panel {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .user-card {
        display: flex;
        background: #fff;
        border-radius: 6px;
        padding: 14px;
        align-items: center;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        .avatar {
          width: 48px;
          height: 48px;
          border-radius: 50%;
          margin-right: 12px;
        }
        .hello {
          font-weight: 600;
          color: #333;
          margin: 0 0 8px 0;
        }
        .auth-actions .el-button + .el-button {
          margin-left: 8px;
        }
      }

      .quick-links {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        background: #fff;
        border-radius: 6px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        
        .ql-item {
          height: 64px;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          color: #333;
          cursor: pointer;
          transition: background 0.2s ease;
          &:hover {
            background: #f7f7f7;
          }
          :deep(.el-icon) {
            margin-bottom: 4px;
            color: #ff1e32;
          }
        }
      }

      .right-promos {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 12px;
        .promo {
          background: #fff;
          border-radius: 6px;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
          
          cursor: pointer;
          display: flex;
          align-items: center;
          img {
            width: 60px;
            height: 60px;
            object-fit: cover;
          }
          span {
            padding: 0 8px;
            font-size: 12px;
            color: #333;
          }
        }
      }
    }
  }

  .mobile-hero {
    display: none; /* Hidden by default */
    margin-top: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    .mobile-carousel {
      border-radius: 6px;
      
      box-shadow: 0 2px 8px rgba(0,0, 0, 0.1);
      margin-bottom: 15px;

      .mobile-banner-container {
        position: relative;
        cursor: pointer;
        height: 100%;

        .mobile-banner-image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }

        .mobile-banner-overlay {
          position: absolute;
          bottom: 0;
          left: 0;
          right: 0;
          background: linear-gradient(transparent, rgba(0, 0, 0, 0.7));
          color: white;
          padding: 40px 20px 20px;
          text-align: center;

          h3 {
            font-size: 24px;
            font-weight: bold;
            margin: 0 0 8px 0;
          }
          p {
            font-size: 14px;
            margin: 0;
            opacity: 0.9;
          }
        }
      }
    }

    .mobile-category-menu {
      margin-bottom: 15px;
      .mobile-category-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 10px;
        h3 {
          font-size: 18px;
          font-weight: bold;
          color: #333;
          margin: 0;
        }
      }
      .mobile-category-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 10px;
        .mobile-category-item {
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          color: #333;
          cursor: pointer;
          transition: background 0.2s ease;
          &:hover {
            background: #f7f7f7;
          }
          :deep(.el-icon) {
            margin-bottom: 4px;
            color: #ff1e32;
          }
        }
      }
    }

    .mobile-user-actions {
      margin-bottom: 15px;
      .mobile-user-card {
        display: flex;
        align-items: center;
        background: #fff;
        border-radius: 6px;
        padding: 14px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
        .mobile-avatar {
          width: 48px;
          height: 48px;
          border-radius: 50%;
          margin-right: 12px;
        }
        .mobile-user-info {
          .mobile-hello {
            font-weight: 600;
            color: #333;
            margin: 0 0 8px 0;
          }
          .mobile-user-buttons .el-button + .el-button {
            margin-left: 8px;
          }
        }
      }
      .mobile-auth-card {
        display: flex;
        align-items: center;
        background: #fff;
        border-radius: 6px;
        padding: 14px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0);
        .mobile-auth-info {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          text-align: center;
          width: 100%;
          height: 100%;
          
          .mobile-welcome {
            font-weight: 600;
            color: #333;
            margin: 0 0 8px 0;
          }
          
          .mobile-auth-buttons {
            display: flex;
            gap: 8px;
            justify-content: center;
            
            .el-button + .el-button {
              margin-left: 0;
            }
          }
        }
      }
    }

    .mobile-quick-links {
      display: flex;
      justify-content: space-around;
      background: #fff;
      border-radius: 6px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0);
      .mobile-quick-grid {
        display: grid;
        grid-template-columns: repeat(4, 1fr);
        gap: 10px;
        .mobile-quick-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          font-size: 12px;
          color: #333;
          cursor: pointer;
          transition: background 0.2s ease;
          &:hover {
            background: #f7f7f7;
          }
          :deep(.el-icon) {
            margin-bottom: 12px;
            color: #ff1e32;
            transform: scale(2); // 增加图标大小
          }
        }
      }
    }
  }

  .mobile-category-drawer {
    .mobile-category-list {
      .mobile-category-list-item {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding: 10px 15px;
        font-size: 14px;
        color: #333;
        cursor: pointer;
        transition: background 0.2s ease;
        &:hover {
          background: #f7f7f7;
        }
        .category-name {
          flex: 1;
          text-overflow: ellipsis;
          
          white-space: nowrap;
        }
        :deep(.el-icon) {
          margin-left: 10px;
          color: #ff1e32;
        }
      }
    }
  }

  .quick-nav-section {
    margin-bottom: 30px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    .quick-nav-grid {
      display: grid;
      /* 使用auto-fit和minmax实现响应式网格 */
      grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
      gap: 20px;
      /* 确保网格居中 */
      justify-content: center;
      margin: 0 auto;
    }

    .quick-nav-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;
      padding: 15px 10px;
      border-radius: 8px;
      transition: all 0.3s ease;
      /* 确保每个项目的最小宽度 */
      min-width: 80px;

      &:hover {
        background: #fff5f0;
        transform: translateY(-2px);
      }

      .nav-icon {
        width: 40px;
        height: 40px;
        background: #ff6b35;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 10px;
        color: white;
        font-size: 18px;
      }

      .nav-text {
        font-size: 13px;
        color: #333;
        text-align: center;
        font-weight: 500;
        /* 确保文字不会换行 */
        white-space: nowrap;
        
        text-overflow: ellipsis;
        max-width: 100%;
      }
    }
  }

  .section-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 0 20px;

    .section-title {
      font-size: 24px;
      font-weight: bold;
      color: #333;
      margin: 0;
      position: relative;

      &::after {
        content: '';
        position: absolute;
        bottom: -5px;
        left: 0;
        width: 40px;
        height: 3px;
        background: #ff6b35;
        border-radius: 2px;
      }
    }

    .more-btn {
      color: #ff6b35;
      font-weight: 500;

      &:hover {
        color: #e55a2b;
      }
    }
  }

  .category-section {
    margin-bottom: 40px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    @media (max-width: 768px) {
      display: none; // 在移动端隐藏
    }

    .category-grid {
      display: grid;
      grid-template-columns: repeat(8, 1fr);
      gap: 20px;

      .category-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;
        padding: 15px 10px;
        border-radius: 8px;
        transition: all 0.3s ease;

        &:hover {
          background: #fff5f0;
          transform: translateY(-3px);
        }

        .category-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          margin-bottom: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          color: white;
          font-size: 24px;
          transition: transform 0.3s ease;

          :deep(.el-icon) {
            font-size: 24px;
          }
        }

        .category-name {
          font-size: 14px;
          color: #666;
          text-align: center;
          font-weight: 500;
        }
      }
    }
  }

  .products-section {
    margin-bottom: 40px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    .products-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
      gap: 20px;
    }
  }

  .brands-section {
    margin-bottom: 40px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);

    .brands-grid {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
      gap: 20px;
      max-width: 100%;
      overflow: hidden;

      .brand-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        cursor: pointer;
        padding: 20px 15px;
        border: 1px solid #f0f0f0;
        border-radius: 8px;
        transition: all 0.3s ease;
        min-width: 0; /* 防止内容撑大 */
        width: 100%;

        &:hover {
          border-color: #ff6b35;
          box-shadow: 0 4px 12px rgba(255, 107, 53, 0.15);
          transform: translateY(-2px);
        }

        .brand-logo {
          width: 80px;
          height: 40px;
          margin-bottom: 10px;
          display: flex;
          align-items: center;
          justify-content: center;
          flex-shrink: 0;

          img {
            max-width: 100%;
            max-height: 100%;
            object-fit: contain;
          }
        }

        .brand-name {
          font-size: 14px;
          color: #666;
          font-weight: 500;
          text-align: center;
          word-break: break-word;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          max-width: 100%;
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .home-container {
    padding: 0 10px;

    /* 隐藏桌面端布局 */
    .desktop-only {
      display: none !important;
    }

    .hero-grid {
      grid-template-columns: 1fr; /* Stack on mobile */
      gap: 10px;
    }

    .category-menu {
      display: none; /* Hide desktop category menu on mobile */
    }

    .hero-carousel {
      grid-column: 1 / -1; /* Take full width */
      height: 200px; /* Adjust carousel height for mobile */
    }

    .user-panel {
      grid-column: 1 / -1; /* Take full width */
      flex-direction: row; /* Arrange user panel items horizontally */
      justify-content: space-between;
      align-items: center;
      padding: 10px 15px;
      .user-card {
        flex: 1;
        margin-right: 10px;
      }
      .quick-links {
        flex: 1;
        grid-template-columns: repeat(4, 1fr);
        gap: 10px;
      }
      .right-promos {
        display: none; /* Hide desktop right promos on mobile */
      }
    }

    .mobile-hero {
      display: block; /* Show mobile hero on mobile */
    }

    .quick-nav-grid {
      grid-template-columns: repeat(4, 1fr);
      gap: 15px;
      max-width: none; /* 移动端不限制最大宽度 */
      
      .quick-nav-item {
        min-width: auto; /* 移动端不限制最小宽度 */
        padding: 12px 8px;
        
        .nav-icon {
          width: 32px;
          height: 32px;
          font-size: 16px;
        }
        
        .nav-text {
          font-size: 11px;
        }
      }
    }

    .category-grid {
      grid-template-columns: repeat(4, 1fr);
      gap: 15px;
    }

    .products-grid {
      grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
      gap: 15px;
    }

    .brands-grid {
      grid-template-columns: repeat(3, 1fr);
      gap: 15px;
      
      .brand-item {
        padding: 15px 10px;
        
        .brand-logo {
          width: 60px;
          height: 30px;
        }
        
        .brand-name {
          font-size: 12px;
        }
      }
    }

    .section-header {
      padding: 0 10px;

      .section-title {
        font-size: 20px;
      }
    }
  }
}

@media (max-width: 480px) {
  .home-container {
    /* 隐藏桌面端布局 */
    .desktop-only {
      display: none !important;
    }
    
    .quick-nav-grid {
      grid-template-columns: repeat(3, 1fr); /* 小屏幕显示3列 */
      gap: 12px;
      
      .quick-nav-item {
        padding: 10px 6px;
        
        .nav-icon {
          width: 28px;
          height: 28px;
          font-size: 14px;
        }
        
        .nav-text {
          font-size: 10px;
        }
      }
    }

    .category-grid {
      grid-template-columns: repeat(3, 1fr);
    }

    .brands-grid {
      grid-template-columns: repeat(2, 1fr);
      gap: 12px;
      
      .brand-item {
        padding: 12px 8px;
        
        .brand-logo {
          width: 50px;
          height: 25px;
        }
        
        .brand-name {
          font-size: 11px;
        }
      }
    }
  }
}

/* 中等屏幕优化 */
@media (min-width: 769px) and (max-width: 1024px) {
  .home-container {
    /* 显示桌面端布局 */
    .desktop-only {
      display: grid !important;
    }
    
    /* 隐藏移动端布局 */
    .mobile-only {
      display: none !important;
    }
    
    .quick-nav-grid {
      grid-template-columns: repeat(auto-fit, minmax(90px, 1fr));
      gap: 16px;
      max-width: 600px;
    }
    
    .brands-grid {
      grid-template-columns: repeat(4, 1fr);
      gap: 18px;
      
      .brand-item {
        padding: 18px 12px;
        
        .brand-logo {
          width: 70px;
          height: 35px;
        }
        
        .brand-name {
          font-size: 13px;
        }
      }
    }
  }
}

/* 大屏幕优化 */
@media (min-width: 1025px) {
  .home-container {
    /* 显示桌面端布局 */
    .desktop-only {
      display: grid !important;
    }
    
    /* 隐藏移动端布局 */
    .mobile-only {
      display: none !important;
    }
    
    .quick-nav-grid {
      /* 宽屏上展开成一排 */
      grid-template-columns: repeat(8, 1fr);
      gap: 20px;
      max-width: 100%;
      justify-content: space-between;
    }
    
    .quick-nav-item {
      min-width: auto;
      
      .nav-icon {
        width: 36px;
        height: 36px;
        font-size: 16px;
      }
      
      .nav-text {
        font-size: 12px;
      }
    }
    
    .brands-grid {
      grid-template-columns: repeat(6, 1fr);
      gap: 20px;
      max-width: 1200px;
      margin: 0 auto;
      
      .brand-item {
        padding: 20px 15px;
        
        .brand-logo {
          width: 80px;
          height: 40px;
        }
        
        .brand-name {
          font-size: 14px;
        }
      }
    }
  }
}

/* 超大屏幕优化 */
@media (min-width: 1400px) {
  .home-container {
    /* 显示桌面端布局 */
    .desktop-only {
      display: grid !important;
    }
    
    /* 隐藏移动端布局 */
    .mobile-only {
      display: none !important;
    }
    
    .quick-nav-grid {
      /* 超大屏幕上保持8列但增加间距 */
      gap: 24px;
      max-width: 1200px;
      margin: 0 auto;
    }
    
    .quick-nav-item {
      .nav-icon {
        width: 38px;
        height: 38px;
        font-size: 17px;
      }
      
      .nav-text {
        font-size: 13px;
      }
    }
    
    .brands-grid {
      grid-template-columns: repeat(8, 1fr);
      gap: 24px;
      max-width: 1400px;
      margin: 0 auto;
      
      .brand-item {
        padding: 24px 18px;
        
        .brand-logo {
          width: 90px;
          height: 45px;
        }
        
        .brand-name {
          font-size: 15px;
        }
      }
    }
  }
}
</style>
